package com.tlw.practice.tlw.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tlw.practice.tlw.common.ResultCode;
import com.tlw.practice.tlw.utils.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getMethod().toUpperCase().equals("OPTIONS")){
            return true;//通过所有OPTION请求
        }
        Map<String, Object> map = new HashMap<>();
        // 获取请求头中的token
        String token = request.getHeader("X-Token");
//        String token = request.getQueryString();
        try {
            DecodedJWT verify = JWTUtils.verify(token);     // 验证token
            return true;                // 放行
        }catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg", "无效签名");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg", "token过期");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg", "token算法不一致");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "token无效");
        }
        map.put("state", false);
        String json = new ObjectMapper().writeValueAsString(map);
        // 设置返回编码
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        // 设置跨域
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        return false;
    }
}
